package App.Model;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

//用于限制JTextArea的最大输入
public class LimitFilter extends DocumentFilter {
    private int maxLength;

    public LimitFilter(int maxLength) {
        this.maxLength = maxLength;
    }

    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException {
        if (text != null && text.length() > maxLength) {
            text = text.substring(0, maxLength);
        }
        fb.insertString(offset, text, attrs);
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        if (text != null && text.length() > maxLength) {
            text = text.substring(0, maxLength);
        }
        fb.replace(offset, length, text, attrs);
    }
}
